package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import com.example.demo.utils.FileUtils;
import com.example.demo.utils.ValidateCodeUtils;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.demo.dto.CustomerServiceConnection;
import com.example.demo.dto.ResponseResult;
import com.example.demo.exception.ConnectionNotFound;
import com.example.demo.service.impl.UserServiceImpl;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;


@RequestMapping("app/user")
@RestController
public class UserController {

    @Autowired
    private UserServiceImpl userServiceImpl;
    @Autowired
    private UserService userService;


    @Autowired
    public UserController(UserServiceImpl userServiceImpl) {
        this.userServiceImpl = userServiceImpl;
    }


    // 通过账户密码登录接口
    @PostMapping("/post/login")
    public ResponseResult<User> login(@RequestBody Map<String,String> request){
        String phone = request.get("phone");
        String password = request.get("password");
        try {
            User user = userService.login(phone, password);
            if (user != null) {
                user.setPassword(null);
                return new ResponseResult<>(200, "success", user);
            } else {
                return new ResponseResult<>(400, "用户不存在", null);
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
            return new ResponseResult<>(500,"登录失败: " + e.getMessage(),null);
        }
    }

    // 退出登录接口
    @PostMapping("/post/logout")
    public ResponseResult<Void> logout(
            HttpSession session,
            @RequestParam int userId) {
        try {
            // 更新最后活跃时间
            boolean success = userService.logout(userId);
            if (success) {
                // 清除会话信息
                session.invalidate();
                return new ResponseResult<>(200, "退出登录成功");
            } else {
                return new ResponseResult<>(400, "退出登录失败");
            }
        } catch (Exception e) {
            return new ResponseResult<>(500, "退出登录出错: " + e.getMessage());
        }
    }


    // 发送验证码接口
    @GetMapping("/get/sendMsg")
    public ResponseResult<Integer> sendMsg(@RequestParam String phone){
        try{
            Integer code = userService.sendMsg(phone);
            if (code != null && ValidateCodeUtils.flag){
                // 将验证码保存到codeMap中
                ValidateCodeUtils.codeMap.put(phone,code);

                return new ResponseResult<>(200,"success",code);
            } else {
                // 注册号码，更新表示
                ValidateCodeUtils.flag = true;
                // 将验证码保存到codeMap中
                ValidateCodeUtils.codeMap.put(phone,code);
                return new ResponseResult<>(201,"号码尚未注册",code);
            }
        } catch (Exception e) {
            return new ResponseResult<>(500,"获取验证码失败: " + e.getMessage(),null);
        }
    }


    // 验证码登录接口
    @GetMapping("/get/checkCode")
    public ResponseResult<User> checkMsg(@RequestParam String phone, @RequestParam Integer code){
        try {
            User user = userService.checkMsg(phone, code);
            if(user != null){
                user.setPassword(null);
                return new ResponseResult<>(200,"success",user);
            } else{
                return new ResponseResult<>(400,"验证码或电话号码错误",null);
            }
        } catch (Exception e) {
            return new ResponseResult<>(500,"验证码登录失败：" + e.getMessage(),null);
        }
    }

    // 通过验证码修改密码接口
    @PostMapping("/post/updatePasswordByCode")
    public ResponseResult<Void> updatePasswordByCode(@RequestBody Map<String,String> request){
        Integer userId = Integer.valueOf(request.get("userId"));
        Integer code = Integer.valueOf(request.get("code"));
        String phone = request.get("phone");
        String newPassword = request.get("newPassword");
        try {
            boolean flag = userService.changePassword(userId,newPassword,phone,code);
            if(flag){
                return new ResponseResult<>(200,"success",null);
            }else {
                return new ResponseResult<>(400,"更新异常",null);
            }
        } catch (Exception e) {
            return new ResponseResult<>(500,"修改失败: " + e.getMessage(),null);
        }
    }

    // 账号注销接口
    @DeleteMapping("/post/revokeAccount")
    public ResponseResult<Void> revokeAccount(
            @RequestParam Integer code,
            @RequestParam String phone) {
        System.out.println("打印一下，看是否可以调用");
        try {
            boolean success = userService.revokeAccount(phone, code);
            if (success) {
                return new ResponseResult<>(200, "账号注销成功");
            } else {
                return new ResponseResult<>(400, "验证码错误或账号不存在");
            }
        } catch (Exception e) {
            return new ResponseResult<>(500, "注销账号出错: " + e.getMessage());
        }
    }


    // 个人资料查看接口(测试用的，不作为正式使用)
    @RequestMapping("/post/info")
    public ResponseResult<User> getUserInfo(@RequestParam int id) {
        User user = userService.getById(id);

        return new ResponseResult<>(200, "success", user);
    }

    // 个人资料查看接口
    @GetMapping("/get/profile")
    public ResponseResult<User> getUserProfile(@RequestParam int userId) {
        try {
            User user = userService.getUserProfile(userId);

            if (user != null) {
                return new ResponseResult<>(200, "success", user);
            } else {
                return new ResponseResult<>(400, "用户不存在");
            }
        } catch (Exception e) {
            return new ResponseResult<>(500, "获取个人资料失败: " + e.getMessage());
        }
    }

    // 头像设置接口
    @PostMapping("/post/updateHead")
    public ResponseResult<String> updateUserHead(
            @RequestParam int userId,
            @RequestParam MultipartFile file) {
        System.out.println("userId = " + userId);
        System.out.println(file);
        try {
            // 处理上传文件，转化为在线地址
            FileUtils fileUtils = new FileUtils();
            String headUrl = fileUtils.uploadFile(file);
            boolean success = userService.updateUserHead(userId, headUrl);
            if (success) {
                System.out.println(headUrl + "     头像更新成功！");
                return new ResponseResult<>(200, "头像更新成功",headUrl);
            } else {
                return new ResponseResult<>(400, "头像更新失败",null);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return new ResponseResult<>(500, "更新头像出错: " + e.getMessage(),null);
        }
    }

    // 基本信息管理接口
    @PostMapping("/post/updateInfo")
    public ResponseResult<Void> updateUserInfo(@RequestBody Map<String,String> request) {
        int userId = Integer.parseInt(request.get("userId"));
        String nickname = request.get("nickname");
        String gender = request.get("gender");
        Integer age = request.get("age") == null ? null : Integer.parseInt(request.get("age"));
        String email = request.get("email");
        try {
            boolean success = userService.updateUserInfo(userId, nickname, gender, age, email);
            if (success) {
                return new ResponseResult<>(200, "基本信息更新成功");
            } else {
                return new ResponseResult<>(400, "基本信息更新失败");
            }
        } catch (Exception e) {
            return new ResponseResult<>(500, "更新基本信息出错: " + e.getMessage());
        }
    }

    // 修改密码接口
    @PostMapping("/post/updatePassword")
    public ResponseResult<Void> updatePassword(@RequestBody Map<String, Object> params) {
        int userId = (int)params.get("userId");
        String oldPassword = params.get("oldPassword").toString();
        String newPassword = params.get("newPassword").toString();
        System.out.println("这是userId: " + userId + "  \n   " + "这是oldPassword: " + oldPassword + " \n   " + "这是newPassword: " + newPassword);
        try {
            boolean success = userService.changePassword(userId, oldPassword, newPassword);
            if (success) {
                return new ResponseResult<>(200, "密码更新成功");
            } else {
                return new ResponseResult<>(400, "旧密码不正确或更新失败");
            }
        } catch (Exception e) {
            return new ResponseResult<>(500, "更新密码出错: " + e.getMessage());
        }
    }

    @GetMapping("/get/connection")
    public ResponseResult<CustomerServiceConnection> getConnection() {
        CustomerServiceConnection customerServiceConnection;
        try {
            customerServiceConnection = userServiceImpl.getCustomerServiceConnection();
        } catch (ConnectionNotFound e) {
            return new ResponseResult<>(501, e.getMessage(), new CustomerServiceConnection());
        }
        return new ResponseResult<>(200, "响应成功！", customerServiceConnection);
    }

    //将未被加密密码的用户重新加密（后端更新密码用）
    @PostMapping("/post/encryptUserPassword")
    public ResponseResult<Void> encryptUserPassword(
            @RequestParam int userId,
            @RequestParam String password) {

        try {
            boolean success = userService.encryptUserPassword(userId, password);
            if (success) {
                return new ResponseResult<>(200, "密码更新成功");
            } else {
                return new ResponseResult<>(400, "更新失败:不是该用户密码");
            }
        } catch (Exception e) {
            return new ResponseResult<>(500, "更新密码出错: " + e.getMessage());
        }
    }

}
